import 'dart:async';

import 'package:connectivity_plus/connectivity_plus.dart'; // 🔥 恢复网络监听导入
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:permission_handler/permission_handler.dart';
///JoyNoNetworkTipWidget
typedef HaveNetWorkCallBack=void Function();
//没网的回调
typedef NoNetWorkCallBack=void Function();
class JoyNoNetworkTipWidget extends StatefulWidget{
  HaveNetWorkCallBack? haveNetWorkCallBack;
  NoNetWorkCallBack? noNetWorkCallBack;
  JoyNoNetworkTipWidget({Key? key,this.haveNetWorkCallBack,this.noNetWorkCallBack}):super(key: key);
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return JoyNoNetworkTipWidgetState();
  }

}
class JoyNoNetworkTipWidgetState extends State<JoyNoNetworkTipWidget>{
  StreamSubscription<List<ConnectivityResult>>? netWorkSubscription; 
  bool showNoNetWork=false; // 默认设置为false，表示有网络连接
  bool _isFirstTimeNetworkCheck = true; // 🔥 标记是否是首次网络检查

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      // 🔥 安全地启动网络监听，包含错误处理
      _safeAddNetWorkListener();
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    // 🔥 安全地取消网络订阅
    try {
      netWorkSubscription?.cancel();
    } catch (e) {
      debugPrint('网络订阅取消失败: $e');
    }
  }
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    if (!showNoNetWork) {
      return SizedBox.shrink(); // 完全不占用空间
    }
    return buildMain();
  }

  Widget buildMain()=>GestureDetector(
    onTap: (){
      openAppSettings();
    },
    child: Container(
      decoration: BoxDecoration(
          color: Color(0xfff8dddc),
          borderRadius: BorderRadius.circular(4.w)
      ),
      padding: EdgeInsets.only(top: 6.w,bottom: 6.w),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          SizedBox(width: 10.w,),
          Icon(
            Icons.error,
            color: Colors.redAccent,
          ),
          SizedBox(width: 6.w,),
          Expanded(
            child: Text("Network unavailable, please check your network settings", style: TextStyle(color: Colors.redAccent,fontSize: 12.sp),),
          ),
          Icon(
            Icons.chevron_right,
            color: Colors.redAccent,
          ),
          SizedBox(width: 6.w,),

        ],
      ),
    ),
  );


  // 🔥 安全的网络监听方法，包含错误处理
  void _safeAddNetWorkListener() async {
    try {
      List<ConnectivityResult> connectivityResult = await (Connectivity().checkConnectivity());
      handleResult(connectivityResult);
      netWorkSubscription = Connectivity().onConnectivityChanged.listen(
        (List<ConnectivityResult> connectivityResult) {
          handleResult(connectivityResult);
        },
        onError: (error) {
          debugPrint('网络状态监听错误: $error');
          // 发生错误时假设有网络连接，避免误判
          setState(() {
            showNoNetWork = false;
          });
        },
      );
      debugPrint('网络状态监听启动成功');
    } catch (e) {
      debugPrint('网络状态监听启动失败: $e');
      // 启动失败时默认显示有网络，避免误判
      setState(() {
        showNoNetWork = false;
      });
    }
  }
  // 🔥 优化网络状态处理方法 - 只在首次网络授权时自动刷新
  void handleResult(List<ConnectivityResult> connectivityResult) {
    try {
      bool wasNoNetwork = showNoNetWork;
      
      if (connectivityResult.contains(ConnectivityResult.mobile)) {
        // Mobile network available.
        debugPrint('ConnectivityResult: mobile network available');
        showNoNetWork = false;
      } else if (connectivityResult.contains(ConnectivityResult.wifi)) {
        // Wi-fi is available.
        debugPrint('ConnectivityResult: wifi network available');
        showNoNetWork = false;
      } else if (connectivityResult.contains(ConnectivityResult.ethernet)) {
        debugPrint('ConnectivityResult: ethernet network available');
        showNoNetWork = false;
      } else if (connectivityResult.contains(ConnectivityResult.vpn)) {
        // Vpn connection active.
        debugPrint('ConnectivityResult: vpn network available');
        showNoNetWork = false;
      } else if (connectivityResult.contains(ConnectivityResult.bluetooth)) {
        debugPrint('ConnectivityResult: bluetooth network available');
        showNoNetWork = false;
      } else if (connectivityResult.contains(ConnectivityResult.other)) {
        // Connected to a network which is not in the above mentioned networks.
        debugPrint('ConnectivityResult: other network available');
        showNoNetWork = false;
      } else if (connectivityResult.contains(ConnectivityResult.none)) {
        debugPrint('ConnectivityResult: no network available');
        showNoNetWork = true;
      }
      
      // 🔥 只在首次网络检查且从无网变为有网时，触发自动刷新回调
      if (wasNoNetwork && !showNoNetWork && _isFirstTimeNetworkCheck) {
        debugPrint('首次网络权限授权 - 网络已恢复，触发自动刷新');
        _isFirstTimeNetworkCheck = false; // 标记已完成首次检查
        if (widget.haveNetWorkCallBack != null) {
          widget.haveNetWorkCallBack!();
        }
      } else if (wasNoNetwork && !showNoNetWork && !_isFirstTimeNetworkCheck) {
        debugPrint('非首次网络恢复 - 不自动刷新，等待用户手动操作');
        // 不触发自动刷新回调，让用户手动操作
      } else if (!wasNoNetwork && showNoNetWork) {
        debugPrint('网络已断开，设置错误状态');
        if (widget.noNetWorkCallBack != null) {
          widget.noNetWorkCallBack!();
        }
      }
      
      // 如果首次检查就有网络，则标记为已完成首次检查
      if (_isFirstTimeNetworkCheck && !showNoNetWork) {
        _isFirstTimeNetworkCheck = false;
        debugPrint('首次检查网络状态：有网络连接');
      }
      
      setState(() {});
    } catch (e) {
      debugPrint('网络状态处理错误: $e');
      // 发生错误时保持当前状态，避免误判
    }
  }
}